package cn.mobieteam.add.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.util.Log;

public class HttpUtil {
	private String jSONString;
	private String TAG = "httpTools";
	private String IP = "192.168.0.103"; // 服务器的ip地址
	private int port = 8080; // 服务器的端口号
	private String result = null;

	public HttpUtil() {

	}

	public String POST(Map<String, String> map, String ACTION) {
		try {
			String pathURL = "http://" + IP + ":" + port + "/AddServer/";
			// String pathURL =
			// "http://ys1213hotelorder.jd-app.com/AddServer";
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(pathURL);

			List params = new ArrayList();
			params.add(new BasicNameValuePair("json", getJson(map)));

			httppost.setEntity(new UrlEncodedFormEntity(params));

			HttpResponse response = httpclient.execute(httppost);
			int code = response.getStatusLine().getStatusCode();

			System.out.println("链接成功返回代码" + code);
			if (code == 200) {

				StringBuilder sBuilder = new StringBuilder();

				BufferedReader br = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent()));
				String line = "";
				while ((line = br.readLine()) != null) {
					sBuilder.append(line);
				}
				result = sBuilder.toString();
				System.out.println("gethttpclient中输出   .." + result);
			}
			httpclient.getConnectionManager().shutdown();
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "UnsupportedEncodingException");
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			Log.e(TAG, "ClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, "IOException");
			e.printStackTrace();
		}
		return result;
	}

	public String getJson(Map<String, String> params) {
		JSONObject jsonRequest = new JSONObject();
		try {
			if (params != null) {
				for (String key : params.keySet()) {
					jsonRequest.put(key, params.get(key));
				}
			}
			jSONString = jsonRequest.toString();
		} catch (Exception e) {
		}
		return jSONString;
	}
}
